package org.example.mulitithreading.ex2p;

public class SellTicket4 implements Runnable{
    private int ticketCount = 100;

    @Override
    public void run() {
        while(true){ // 使用静态同步方法时，两个线程的唯一锁是 SellTicket4对象本身(this)
            if("窗口1".equals(Thread.currentThread().getName())){
                //同步方法
                boolean result = synchronizedMethod();
                if(result){
                    break;
                }
            }
            if("窗口2".equals(Thread.currentThread().getName())){
                //同步代码块
                synchronized (this){
                    if(ticketCount == 0){
                        break;
                    }else{
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ticketCount--;
                        System.out.println(Thread.currentThread().getName() + "在卖票,还剩下" + ticketCount + "张票");
                    }
                }
            }
        }
    }

    private synchronized boolean synchronizedMethod() {
        if(ticketCount == 0){
            return true;
        }else{
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticketCount--;
            System.out.println(Thread.currentThread().getName() + "在卖票,还剩下" + ticketCount + "张票");
            return false;
        }
    }
}
